<template>
  <div>
    <section class="header">
      <a-page-header class="header" title="收据记录">
        <template #extra>
          <a-button @click="btnImport">
            <UploadOutlined/>
            批量导入
          </a-button>
        </template>
      </a-page-header>
    </section>
    <section class="box">
      <section>
        <a-row class="quantity" type="flex" justify="space-around" wrap="true">
          <a-col class="text-center">
            <div class="text">开据金额</div>
            <div class="number-width">￥{{ sum_price }}</div>
          </a-col>
          <a-col class="text-center">
            <div class="text">未发出收据数</div>
            <div class="number-width">{{ noSend_total }}</div>
          </a-col>
          <a-col class="text-center">
            <div class="text">开据数</div>
            <div class="number-width">{{ total }}</div>
          </a-col>
        </a-row>
      </section>
      <section class="table">
        <a-table
            sticky
            :columns="columns"
            :dataSource="dataSource"
            :loading="loading"
            rowKey="id"
            :scroll="{ x: 'max-content' }"
            :rowSelection="rowSelection"
            @change="onChange"
            :pagination="pagination"
            :customRow="customRow"
        >
          <template #title>
            <a-row type="flex" justify="space-between" wrap="true">
              <a-col>
                <a-range-picker
                    v-model:value="rangeTime"
                    :placeholder="['创建起始时间', '创建结束时间']"
                    :value-format="dateFormatStr"
                    @change="handleRangePickerChange"
                />
              </a-col>
              <a-col>
                <a-space>
                  <a-button :disabled="recoveryDisabled" @click="recoveryClick"
                  >回收
                  </a-button>
                  <a-button
                      class="btn-class"
                      :disabled="issueDisabled"
                      @click="issueClick"
                  >发出
                  </a-button>
                  <a-button
                      class="btn-class"
                      @click="generateTemplate"
                      :disabled="!selectedRows.length"
                  >生成
                  </a-button>
                  <a-button
                      class="btn-class"
                      @click="printReceipt"
                      :disabled="!selectedRows.length"
                  >打印
                  </a-button>
                  <span v-show="!selectedRows.length">
                    <custom-columns
                        :colUrl="colUrl"
                        type="user_receipt_list_field"
                        resetType="autoInvoiceListColumn"
                        @getColumns="getColumns"
                    />
                  </span>
                </a-space>
              </a-col>
            </a-row>
          </template>
          <template
              #customFilterDropdown="{
              setSelectedKeys,
              selectedKeys,
              confirm,
              clearFilters,
              column,
            }"
          >
            <div style="padding: 8px">
              <a-input
                  ref="searchInput"
                  :placeholder="`搜索 ${column.title}`"
                  :value="selectedKeys[0]"
                  style="width: 188px; margin-bottom: 8px; display: block"
                  @change="
                  (e) => setSelectedKeys(e.target.value ? [e.target.value] : [])
                "
                  @pressEnter="
                  handleSearch(selectedKeys, confirm, column.searchKey)
                "
              />
              <a-button
                  type="primary"
                  size="small"
                  style="width: 90px; margin-right: 8px"
                  @click="handleSearch(selectedKeys, confirm, column.searchKey)"
              >
                搜索
              </a-button>
              <a-button
                  size="small"
                  style="width: 90px"
                  @click="handleReset(clearFilters, confirm, column.searchKey)"
              >
                重置
              </a-button>
            </div>
          </template>
          <template #customFilterIcon="filtered">
            <search-outlined
                :style="{ color: filtered ? '#108ee9' : undefined }"
            />
          </template>
          <template #bodyCell="{ text, record, index, column }">
            <template v-if="column.key === 'status_txt'">
              <!-- 发票状态 -->
              <a-tag v-if="record.status == 1" color="#02b271">
                {{ text }}
              </a-tag>
              <a-tag v-else-if="record.status == 2" color="#9152dd">
                {{ text }}
              </a-tag>
              <a-tag v-else-if="record.status == 3" color="#ff3141">
                {{ text }}
              </a-tag>
              <a-tag v-else-if="record.status == 4" color="#666666">
                {{ text }}
              </a-tag>
              <a-tag v-else-if="record.status == 5" color="#656565">
                {{ text }}
              </a-tag>
              <a-tag v-else color="#1073ff">{{ text }}</a-tag>
            </template>
          </template>
        </a-table>
      </section>
    </section>
    <a-modal
        v-model:visible="visible"
        title="生成收据"
        ok-text="确定并下载"
        @ok="handleOk"
    >
      <a-form layout="vertical">
        <a-form-item label="收据模板">
          <a-select
              v-model:value="tempValue"
              placeholder="Inserted are removed"
              style="width: 100%"
              :options="templateOptions"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!--  批量导入  -->
    <Import
        :visible="visibleImport"
        title="导入收据"
        from="receipt"
        :importUrl="importUrl"
        :downloadTemUrl="downloadTemUrl"
        :showError="true"
        @cancelBtn="visibleImport = false"
        @refresh="importSuccess"
    />

    <!--打印-->
    <print-modal :file_list="printList" :usePrint="showModal" @change="showModal=false"/>

  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  ref,
  onActivated,
} from "vue";
import CustomColumns from "../../../components/CustomColumns/index.vue";
import {
  SearchOutlined,
  UploadOutlined,
  CloudDownloadOutlined,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import {useRouter, useRoute} from "vue-router";
import {message} from "ant-design-vue";
import utils from "../../../common/utils/utils";
import Import from "@/views/setting/DepartmentUser/modules/Import.vue";
import PrintModal from '@/components/Bill/PrintModal.vue'

let CertCtl;
export default defineComponent({
  name: "receiptList",
  components: {
    PrintModal,
    UploadOutlined,
    CustomColumns,
    SearchOutlined,
    Import,
    CloudDownloadOutlined,
  },
  setup() {
    const $router = useRouter();
    const $route = useRoute();

    const state = reactive({
      columns: [],
      loading: false,
      rangeTime: [],
      page: $route.query.page ? Number($route.query.page) : 1,
      pageSize: 20,
      total: 0,
      dataSource: [],
      searchInput: null,
      initData: [],
      colUrl: {server: "/org", url: "/org/receiptListColumn"},
      selectedRows: "",
      noSend_total: 0,
      sum_price: 0,
      sum_total: 0,
      visible: false,
      tempValue: "",
      templateOptions: [],
      selectedRowKeys: [],
      visibleImport: false,
      importUrl: {
        server: "/org",
        url: "/receipt/import",
      },
      downloadTemUrl: {
        server: "/org",
        url: "/invoice/import/receiptFile",
      },
      showModal: false,
      printList: [],
    });
    /* 获取列表展示项 */
    const searchCols = [
      "payment_company",
      "receipt_number",
      "collection_company",
      "cost_name",
      "issuer_uname",
    ];
    const filterCols = ["status_txt"];
    const sorterCols = ["issuer_time", "receipt_amounts"];

    // 自定义行
    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: () => {
          handleTableRowClick(record);
        },
      };
    };
    // 点击行
    const handleTableRowClick = (record) => {
        window.microApp.forceDispatch({
            type: "SetChildDrawerList",
            info: {
              props: {
                title: null,
                maskCloseable: true,
                visible: true,
                closable: false,
                width: 1200,
                bodyStyle: {height: '100%',},
                destroyOnClose: true,
              },
              microId: "org_receipt_detail",
              heightFull: true,
              app: "org",
              url: `/bill/receiptDetail?group_key=${record.group_key}&isClose=true`,
              params: {
                isMainDrawer: true,
              }
            },
        })
    };

    const getListInit = () => {
      request.get("/org", "/receipt/listInit").then((res) => {
        const {initData} = res;
        state.initData = initData.receiptStatus.map((item) => {
          return {
            text: item.name,
            value: item.key,
          };
        });
      });
    };
    getListInit();

    const getColumns = (columns) => {
      state.columns = [];
      columns.forEach((item) => {
        if (item.title == "开据金额") {
          item.key = "receipt_price";
        }
        let newItem = {
          title: item.title,
          key: item.key,
          dataIndex: item.key,
          width: 150,
        };

        if (searchCols.includes(item.key)) {
          newItem.searchKey = item.key;
          newItem.customFilterDropdown = true;
          newItem.onFilterDropdownVisibleChange = (visible) =>
              // searchInputFocus(visible);
              console.log(visible);
        }
        if (filterCols.includes(item.key)) {
          newItem.filters = state.initData;
          newItem.filterMultiple = false;
        }
        if (sorterCols.includes(item.key)) {
          newItem.sorter = true;
        }
        state.columns.push(newItem);
      });
    };

    const searchForm = reactive({
      start_time: undefined,
      end_time: undefined,
      sort: undefined,
      status: undefined,
      receipt_number: undefined,
      collection_company: undefined,
      issuer_uname: undefined,
      cost_name: undefined,
      payment_company: undefined,
    });

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.pageSize,
      showSizeChanger: true,
    }));

    const handleRangePickerChange = (date, dateString) => {
      searchForm.start_time = dateString[0] || undefined;
      searchForm.end_time = dateString[1] || undefined;
      receiptList();
    };
    // 搜索
    const handleSearch = (selectedKeys, confirm, searchKey) => {
      if (selectedKeys && selectedKeys.length > 0) {
        searchForm[searchKey] = selectedKeys[0];
      }
      confirm();
    };
    const handleReset = (clearFilters, confirm, searchKey) => {
      searchForm[searchKey] = undefined;
      clearFilters();
      confirm();
    };
    let group_keys = ref([]);
    const issueDisabled = ref(true);
    const recoveryDisabled = ref(true);
    /* 选择账单行 */
    const rowSelection = computed(() => ({
      selectedRowKeys: state.selectedRowKeys,
      onChange: onSelectedRowChange,
    }));
    const onSelectedRowChange = (selectedRowKeys, selectedRows) => {
      state.selectedRows = selectedRows;
      state.selectedRowKeys = selectedRowKeys;

      if (!state.selectedRows.length) {
        issueDisabled.value = true;
        recoveryDisabled.value = true;
      }
      state.selectedRows.forEach((item) => {
        if (item.status_txt.includes("未发出")) {
          issueDisabled.value = false;
          console.log("有未发出");
        } else {
          issueDisabled.value = true;
        }
        if (item.status_txt.includes("已发出")) {
          recoveryDisabled.value = false;
          console.log("有已发出");
        } else {
          recoveryDisabled.value = true;
        }
      });
      group_keys.value = state.selectedRows.map((item) => {
        return item.group_key;
      });
    };

    const onChange = (pagination, filters, sorter) => {
      let order = "";
      order =
          sorter.order == "ascend"
              ? "asc"
              : sorter.order == undefined
                  ? undefined
                  : "desc";
      state.page = pagination.current;
      state.pageSize = pagination.pageSize;
      searchForm.sort = order;
      searchForm.status = filters.status_txt;
      receiptList();
    };

    // 列表数据
    const receiptList = () => {
      state.loading = true;
      request
          .get("/org", "/receipt/list", {
            page: state.page,
            limit: state.pageSize,
            ...searchForm,
          })
          .then((res) => {
            state.dataSource = res.list;
            state.total = res.total;
            state.noSend_total = res.notIssueNums;
            state.sum_price = res.receiptAmounts;
          });
      state.loading = false;
    };

    // 生成
    const generateTemplate = () => {
      if (state.selectedRows.length >= 20) {
        message.warn("必须小于20条数据才能生成~");
        return;
      }
      request
          .post("/org", "/receipt/getTemplateList", {
            group_keys: group_keys.value,
          })
          .then((res) => {
            state.visible = true;
            state.templateOptions = res.templateList.map((item) => {
              return {
                value: item.id,
                label: item.name,
              };
            });
            state.tempValue = res.templateList[0].id;
          });
    };
    const handleOk = (e) => {
      request
          .post("/org", "/receipt/createBatch", {
            template_id: state.tempValue,
            group_keys: group_keys.value,
          })
          .then((res) => {
            message.success("生成中请耐心等待，稍后可在收据详情进行下载");
            state.visible = false;
          });
    };

    // 发出
    const issueClick = () => {
      utils.modalConfirm({
        content: `是否发送未发出的收据？`,
        centered: true,
        onOk: () => {
          request
              .post("/org", "/receipt/send", {group_keys: group_keys.value})
              .then((res) => {
                message.success("发出收据成功");
                receiptList();
                state.selectedRowKeys = [];
              });
        },
      });
    };
    // 回收
    const recoveryClick = () => {
      utils.modalConfirm({
        content: `是否收回已发出的收据？`,
        centered: true,
        onOk: () => {
          request
              .post("/org", "/receipt/recovery", {group_keys: group_keys.value})
              .then((res) => {
                message.success("发出收据成功");
                receiptList();
                state.selectedRowKeys = [];
              });
        },
      });
    };

    const btnImport = () => {
      state.visibleImport = true;
    };

    const importSuccess = () => {
      state.visibleImport = false;
      receiptList();
    };

    const init = () => {
      receiptList();
    };

    onActivated(() => {
      init();
    });


    const printReceipt = () => {
      const list = state.selectedRows.filter((item) => {
        return item?.apply_template?.fileUrl != undefined;
      })
      if (list.length == 0) {
        message.error("所选数据均未配置收据打印模板，请重新选择！")
        return
      }
      state.printList = list.map((item) => {
        return item.apply_template.fileUrl;
      })
      state.showModal = true;
    };

    return {
      ...toRefs(state),
      dateFormatStr: "YYYY-MM-DD",
      getColumns,
      rowSelection,
      onChange,
      pagination,
      handleRangePickerChange,
      handleSearch,
      handleReset,
      customRow,
      generateTemplate,
      handleOk,
      issueClick,
      recoveryClick,
      issueDisabled,
      recoveryDisabled,
      btnImport,
      importSuccess,
      printReceipt,
    };
  },
});
</script>

<style lang="less" scoped>
.header {
  background-color: #fff;
  margin-left: 1px;
}

.box {
  padding: 15px;
  // height: 100%;
  .quantity {
    width: 100%;
    background-color: #fff;
    height: 120px;
    align-items: center;

    .text-center {
      text-align: center;

      .text {
        color: #8d8d8d;
      }

      .number-width {
        font-weight: 700;
        font-size: 26px;
      }
    }
  }

  .table {
    width: 100%;
    // height: 100%;
    background-color: #fff;
    margin-top: 10px;
    padding: 10px;
    // overflow-y: auto;
    .btn-class {
      margin: 0 5px;
    }
  }
}
</style>
